radarFrequency = 4e9;

antenna = phased.IsotropicAntennaElement;
antenna.FrequencyRange = [1e9 10e9];

wave = phased.LinearFMWaveform;
wave.NumPulses = 1;
wave.PulseWidth = 1e-6;
wave.PRF = 5e3;
wave.OutputFormat = 'Pulses';

target = phased.RadarTarget;
target.Model = 'Nonfluctuating';
target.MeanRCS = 0.5;
target.PropagationSpeed = physconst('LightSpeed');
target.OperatingFrequency = radarFrequency;

radarPlatform = phased.Platform;
radarPlatform.InitialPosition = [0; 0; 0];
radarPlatform.Velocity = [0; 0; 0];

targetPlatform = phased.Platform;
targetPlatform.InitialPosition = [7000; 9600; 0];
targetPlatform.Velocity = [-15; -10; 0];

[targetRange, targetAngle] = rangeangle(targetPlatform.InitialPosition, radarPlatform.InitialPosition);

probDetection = 0.9;
probFalseAlarm = 1e-6;
pulsesCount = 10;
SNR = albersheim(probDetection, probFalseAlarm, pulsesCount);

lambda = physconst('LightSpeed')/radarFrequency;
maxRange = 1.5e4;
tau = wave.PulseWidth;
radarPower = radareqpow(lambda, maxRange, SNR, tau, 'RCS', 0.5, 'Gain', 20);

transmitter = phased.Transmitter;
transmitter.PeakPower = radarPower;
transmitter.Gain = 20;
transmitter.LossFactor = 0;
transmitter.InUseOutputPort = true;
transmitter.CoherentOnTransmit = true;

radiator = phased.Radiator;
radiator.Sensor = antenna;
radiator.OperatingFrequency = radarFrequency;
radiator.PropagationSpeed = physconst('LightSpeed');

collector = phased.Collector;
collector.Sensor = antenna;
collector.OperatingFrequency = radarFrequency;
collector.PropagationSpeed = physconst('LightSpeed');
collector.Wavefront = 'Plane';

receiver = phased.ReceiverPreamp;
receiver.Gain = 20;
receiver.NoiseFigure = 2;
receiver.ReferenceTemperature = 290;
receiver.SampleRate = 1e6;
receiver.EnableInputPort = true;
receiver.SeedSource = 'Property';
receiver.Seed = 1e3;

space = phased.FreeSpace;
space.PropagationSpeed = physconst('LightSpeed');
space.OperatingFrequency = radarFrequency;
space.TwoWayPropagation = false;
space.SampleRate = 1e6;

T = 1/wave.PRF;      %odstęp między kolejnymi pulsami
radarPosition = radarPlatform.InitialPosition;
echo = zeros(wave.SampleRate*T, pulsesCount);

for n = 1:pulsesCount
    targetPosition = targetPlatform.step(T);
    [targetRange, targetAngle] = rangeangle(targetPosition, radarPosition);
    signal = wave.step();
    [signal, transmitterStatus] = transmitter.step(signal);
    signal = radiator.step(signal, targetAngle);
    signal = space.step(signal, radarPosition, targetPosition);
    signal = target.step(signal);
    signal = space.step(signal, targetPosition, radarPosition);
    signal = collector.step(signal, targetAngle);
    echo(:, n) = step(receiver, signal, ~transmitterStatus);
end

echo = pulsint(echo, 'noncoherent');
t = unigrid(0, 1/receiver.SampleRate, T, '[)');
rangegates = physconst('LightSpeed')*t/2;

figure;
hold on;
plot(rangegates, echo);
xlabel('Meters');
ylabel('Power');


